package com.fortune.rainshineservice.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Optional;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.fortune.rainshinecommon.base.MsgModel;
import com.fortune.rainshinecommon.enums.ErrorCodes;
import com.fortune.rainshinecommon.enums.ResultCode;
import com.fortune.rainshinecommon.model.CityModel;
import com.fortune.rainshinecommon.model.CustomerModel;
import com.fortune.rainshinecommon.model.ShopModel;
import com.fortune.rainshinecommon.query.CustomerQuery;
import com.fortune.rainshinecommon.util.UUIDGenerator;
import com.fortune.rainshineservice.mapper.CityMapper;
import com.fortune.rainshineservice.mapper.CustomerMapper;
import com.fortune.rainshineservice.mapper.ShopMapper;
import com.fortune.rainshineservice.mapper.SysUserMapper;
import com.fortune.rainshineservice.service.ICustomerService;
import com.google.common.collect.Lists;

/**
 * @program: rainShine
 * @description:
 * @author: tangyn
 * @create: 2019-03-16
 **/
@Service
public class CustomerServiceImpl implements ICustomerService {
    private static final Logger logger = LoggerFactory.getLogger(CustomerServiceImpl.class);

    @Autowired
    private CustomerMapper customerMapper;

    @Autowired
    private CityMapper cityMapper;

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public MsgModel createCustomer(CustomerModel customerModel) {
        try {
            if(phoneExist(customerModel.getCustomerPhone())){
                return new MsgModel("此手机号已被注册！", ResultCode.FAILURE);
            }
            customerModel.setCustomerCode(UUIDGenerator.generate());
            /*customerModel.setCreateId(customerModel.getUserId());
            customerModel.setUpdateId(customerModel.getUserId());*/
            customerMapper.save(customerModel);
            return new MsgModel("添加顾客成功！", ResultCode.SUCCESS);
        } catch(Exception e) {
            logger.error(ErrorCodes.BUSINESS_EXCEPTION.getMessage(), e);
            return new MsgModel("创建顾客失败！", ResultCode.FAILURE);
        }
    }

    @Override
    public MsgModel customerList(CustomerQuery query) {
        if(query.getUserId() == null){
            return new MsgModel("无此权限！", ResultCode.FAILURE);
        }
        try{
            Wrapper<CustomerModel> wrapper = new EntityWrapper<>();
            Integer roleId = sysUserMapper.getRoleIdByUserId(query.getUserId());
            if(roleId == null){
                return new MsgModel("无此权限！", ResultCode.FAILURE);
            }
            if(query.getShopId() == null){
                if(roleId != 2){
                    return new MsgModel("无此权限！", ResultCode.FAILURE);
                }
            }else {
                if(roleId != 2){
                    ShopModel shopModel = shopMapper.selectById(query.getShopId());
                    if(query.getUserId()!=shopModel.getManagerId()){
                        return new MsgModel("无此权限！", ResultCode.FAILURE);
                    }
                }
                wrapper.eq("shop_id", query.getShopId());
            }
            Page<CustomerModel> page = new Page<>(query.getPage(),query.getLimit());
            List<CustomerModel> list = Optional.ofNullable(customerMapper.selectPage(page,wrapper)).orElse(Lists.newArrayList());
            if(!list.isEmpty()){
                list.forEach(e -> {
                    if(StringUtils.isNotBlank(e.getCityCode())){
                        CityModel cityModel = cityMapper.selectCityByCityCode(e.getCityCode());
                        e.setCityName(cityModel!=null?cityModel.getCityName():e.getCityCode());
                    }
                    if(e.getShopId() != null){
                        ShopModel se = shopMapper.selectById(e.getShopId());
                        e.setShopName(se.getShopName());
                    }
                    /*e.setCreateUser(sysUserMapper.selectUserNameByUserId(e.getCreateId()));
                    e.setUpdateUser(sysUserMapper.selectUserNameByUserId(e.getUpdateId()));*/
                });
            }
            int total = customerMapper.selectCount(wrapper);
            return new MsgModel(total, list);
        } catch (Exception e){
            logger.error("customerList ===>" + e.getMessage());
            return new MsgModel(ResultCode.FAILURE);
        }
    }

    @Override
    public MsgModel updateCustomer(CustomerModel customerModel, String userName) {
        try{
            CustomerModel oldCustomer = customerMapper.selectByCustomerCode(customerModel.getCustomerCode());
            if(!customerModel.getCustomerPhone().equals(oldCustomer.getCustomerPhone()) && phoneExist(customerModel.getCustomerPhone())){
                return new MsgModel("此手机号已被注册！", ResultCode.FAILURE);
            }
//            customerModel.setUpdateId(userName);
            customerModel.setUpdateTime(new Date());
            customerMapper.update(customerModel);
            return new MsgModel("更新顾客信息成功！", ResultCode.SUCCESS);
        } catch (Exception e){
            logger.error(ErrorCodes.BUSINESS_EXCEPTION.getMessage(), e);
            return new MsgModel("更新顾客信息失败！", ResultCode.FAILURE);
        }
    }

    private boolean phoneExist(String phone){
        int c = customerMapper.selectCountByPhone(phone);
        if(c > 0) {
            return true;
        }
        return false;
    }
}
